<template>
  <div class="container">
    <navigate> 发起线下预约 </navigate>

    <div class="card flex_row flex_align_center">
      <img :src="joinUrlImg(info.avatar)" alt="" class="avatar" />
      <div class="name_label flex_column">
        <div class="name">{{ info.name + "(" + info.age + "岁)" }}</div>
        <div class="label flex_row">
          <div class="text nowrap">标签:</div>
          <div class="icon">
            <img
              :src="joinUrlImg(item.tag_icon)"
              :key="index"
              v-for="(item, index) in info.userTag"
              alt=""
            />
          </div>
        </div>
      </div>
      <!-- <div class="status">{{ "可预约" }}</div> -->
    </div>

    <div class="card2">
      <div class="item flex_row flex_align_center between">
        <div class="label">专家性别：</div>
        <div class="val">{{ info.sex == 1 ? "男" : "女" }}</div>
      </div>
      <!-- <div class="item flex_row flex_align_center between">
        <div class="label">我咨询过：</div>
        <div class="val">{{ info.consultant_num }}</div>
      </div> -->
      <div class="item flex_row flex_align_center between">
        <div class="label">负责部门：</div>
        <div class="val">{{ info.responsible_department }}</div>
      </div>
      <div
        class="item flex_row flex_align_center between intro flex_row flex_align_center"
      >
        <div class="label title">专家简介:</div>
        <div class="val detail" @click="checkDet">详情>></div>
      </div>

      <div class="intro_content">
        {{
          info.consultant_introduction
            ? info.consultant_introduction
            : "暂无简介"
        }}
      </div>
    </div>

    <div class="info_title flex_row flex_align_center">
      <div class="bar"></div>
      <div class="text">填写预约信息</div>
    </div>

    <van-cell-group class="input_outer father_relative">
      <van-field
        readonly
        clickable
        v-model="reservationMethod.label"
        label="预约方式："
        placeholder="选择预约方式"
        @click="visibleReservation = true"
      />
      <v-picker
        :columns="reservationMethodList"
        valueKey="label"
        @confirm="selectReservationMethod"
        :isVisible="visibleReservation"
        @cancel="visibleReservation = false"
      />
      <img
        src="@/assets/images/common/right.png"
        class="right vertical_center"
        alt=""
      />
    </van-cell-group>
    <van-cell-group class="input_outer" v-if="reservationMethod.id == 2">
      <van-field v-model="user" label="预约账号:" placeholder="请输入" />
    </van-cell-group>
    <van-cell-group class="input_outer" v-if="reservationMethod.id == 2">
      <van-field
        type="password"
        v-model="password"
        label="账号密码："
        placeholder="请输入"
        @blur="d"
      />
    </van-cell-group>
    <div class="card6" v-if="reservationMethod.id == 2">
      <div class="item user_info flex_row flex_align_start">
        <div class="label flex_align_start">
          <div class="nowrap">用户匹配：</div>
        </div>
        <div class="info flex_column flex_align_start">
          <div class="item flex_row flex_align_center">
            <div class="label">用户姓名：</div>
            <div class="val">{{ matchingInfo.name || "--" }}</div>
          </div>
          <div class="item flex_row flex_align_center">
            <div class="label">学籍状态：</div>
            <div class="val">
              {{ studentStatus(matchingInfo.student_status) || "--" }}
            </div>
          </div>
          <div class="item flex_row flex_align_center">
            <div class="label">手机号码：</div>
            <div class="val">{{ matchingInfo.phone || "--" }}</div>
          </div>
          <div class="item flex_row flex_align_center">
            <div class="label">所在单位：</div>
            <div class="val">{{ matchingInfo.unit_name || "--" }}</div>
          </div>
          <div class="item flex_row flex_align_center">
            <div class="label">部门/班级：</div>
            <div class="val">{{ matchingInfo.department_name || "--" }}</div>
          </div>
          <div class="item flex_row flex_align_center">
            <div class="label">用户性别：</div>
            <div class="val">{{ getSex(matchingInfo.sex) || "--" }}</div>
          </div>
          <div class="item flex_row flex_align_center">
            <div class="label">实际年龄：</div>
            <div class="val">{{ matchingInfo.age || "--" }}</div>
          </div>
          <div class="item flex_row flex_align_center">
            <div class="label">编号/学号：</div>
            <div class="val">{{ matchingInfo.user_number || "--" }}</div>
          </div>
        </div>
      </div>
    </div>

    <van-cell-group class="input_outer father_relative">
      <van-field
        readonly
        clickable
        v-model="currentDate"
        label="预约日期："
        placeholder="选择预约日期"
        @click="dateVisible = true"
      />

      <van-calendar
        v-model="dateVisible"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="selectDate"
        color="#1989fa"
        :formatter="formatter"
        :defaultDate="defaultDate || new Date($route.query.date * 1000)"
      >
        <template v-slot:title>
          {{ calendarTitle }}
        </template>
      </van-calendar>
      <img
        src="@/assets/images/common/right.png"
        class="right vertical_center"
        alt=""
      />
    </van-cell-group>

    <van-cell-group class="input_outer father_relative time_paragraph">
      <van-field
        readonly
        clickable
        v-model="currentTimeParagraph.label"
        label="预约时段："
        placeholder="选择时段"
        @click="timeVisible = true"
      />
      <v-picker
        :columns="timeParagraph(selectTimeParagraph)"
        valueKey="label"
        @confirm="selectTimeParagraphOperate"
        :isVisible="timeVisible"
        @cancel="timeVisible = false"
      />
      <img
        src="@/assets/images/common/right.png"
        class="right vertical_center"
        alt=""
      />
    </van-cell-group>
    <div class="card4">
      <div class="item address flex_row flex_align_center">
        <div class="label">
          <div class="nowrap">咨询地点：</div>
          (线下)
        </div>
        <input
          type="text"
          v-if="isAddress == 0"
          class="address_input"
          v-model="address"
        />
        <div class="val" v-if="isAddress == 1">
          {{ currentTimeParagraph.address }}
        </div>
      </div>
    </div>

    <div class="fill_info_title flex_row flex_align_center">
      <div class="bar"></div>
      <div class="text">填写问题信息</div>
    </div>
    <van-cell-group class="input_outer father_relative">
      <van-field
        readonly
        clickable
        v-model="currentQuestionType.name"
        label="问题类型"
        placeholder="暂未选择"
        @click="visibleQuestionType = true"
      />
      <v-picker
        :columns="questionType"
        valueKey="name"
        @confirm="selectQuestionType"
        :isVisible="visibleQuestionType"
        @cancel="visibleQuestionType = false"
      />
      <img
        src="@/assets/images/common/right.png"
        class="right vertical_center"
        alt=""
      />
    </van-cell-group>
    <div class="card3">
      <div class="describe flex_row flex_align_start">
        <div class="label">问题描述：</div>

        <textarea
          class="textarea"
          v-model="questionDetail"
          placeholder="请输入问题描述。"
        >
        </textarea>
      </div>
    </div>

    <div class="footer flex_row flex_align_center between">
      <div class="checkbox_box flex_row flex_align_center">
        <checkbox @getCheckboxValue="checkboxChange"></checkbox>
        <div class="text">
          我已阅读并同意<span @click="show = true">《咨询服务协议》</span>。
        </div>
      </div>
      <button class="btn" @click="submit(reservationMethod.id)">
        提交预约
      </button>
    </div>
    <consulting-service-agreement :visible="show" @close="show = $event" />
  </div>
</template>

<script>
import {
  queryOfflineConsultInfo,
  queryPersonScheduling,
  offlAppntSubmit,
  queryParSet,
  queryUsernameGetInfo,
} from "@/api/consultation/offline.js";
import selectQuestionType from "@/mixins/selectQuestionType.js";
import { formatDate, getTimestamp, timestampToUTCDate } from "@/utils/time.js";
import { mapState } from "vuex";
import consultingServiceAgreement from "@/components/consultingServiceAgreement/index.vue";
import { joinUrlImg } from "@/utils/setUrlImg";
export default {
  mixins: [selectQuestionType],
  name: "launch2",
  components: {
    consultingServiceAgreement,
  },
  data() {
    return {
      address: "",
      isAddress: null, //选择地址手动还是自动【0手动，1自动】
      scheduleData: [], //每个月的排班

      mothPersonScheduling: [], //每个月排班
      year: new Date().getFullYear(),
      month: new Date().getMonth(),

      // 显示协议
      defaultDate: null,
      show: false,
      info: {},
      // 显示日期
      dateVisible: false,
      // 同意咨询服务协议
      checkbox: false,
      // 预约方式
      reservationMethodList: [
        { label: "本人预约", id: 1 },
        { label: "他人代约", id: 2 },
      ],
      // 选择的预约方式
      reservationMethod: { label: "本人预约", id: 1 },
      // 显示本人还是他们预约
      visibleReservation: false,
      // 可预约的时段
      canBeBooked: [],
      // 当前选择的日期
      currentDate: "",
      // 选择的日期的时段
      selectTimeParagraph: [],
      // 当前时段
      currentTimeParagraph: "",
      // 显示当前时段
      timeVisible: false,
      // 预约地点
      address: "",
      // 问题描述
      questionDetail: "",
      // 用户
      user: "",
      // 密码
      password: "",
      // 防抖
      d: "",
      // 匹配的账号信息
      matchingInfo: {},
      pageData: null,
    };
  },
  computed: {
    ...mapState(["INFO", "TIMER"]),
    minDate() {
      return new Date(this.year, this.month, 1);
    },
    getSex() {
      return (sex) => {
        if (sex == 1) return "男";
        if (sex == 2) return "女";
      };
    },
    // 学籍状态
    studentStatus() {
      return (ss) => {
        if (ss == 1) return "在读";
        if (ss == 2) return "已毕业";
        if (ss == 3) return "已退学";
        if (ss == 4) return "休学";
      };
    },
    calendarTitle() {
      return `${this.year}年${this.month + 1}月`;
    },
    maxDate() {
      return new Date(
        this.year,
        this.month,
        new Date(this.year, this.month + 1, 0).getDate()
      );
    },

    ...mapState({ INFO_USER: (state) => state.INFO }),
    timeParagraph() {
      return (time) => {
        return time.map((item) => {
          return {
            id: item.id,
            label: item.start + "--" + item.end,
            address: item.address,
          };
        });
      };
    },
  },
  watch: {},
  created() {
    this.currentDate = this.convertSecondsToDate(this.$route.query.date);
    this.getAddress();
    this.getUserInfo(this.$route.query.id);
    this.getAppointmentTimePeriod();
  },
  methods: {
    // 获取当前可预约的时间段
    async getAppointmentTimePeriod() {
      let par = {
        date: this.convertTimestampToYearMonth(this.$route.query.date),
        consult_id: this.$route.query.id,
        model: 1,
      };
      let res = await queryPersonScheduling(par);
      if (res.code == 200) {
        this.mothPersonScheduling = res.data;
        this.mothPersonScheduling.forEach((item) => {
          if (item.date == this.$route.query.date) {
            this.selectTimeParagraph = item.time;
          }
        });
      }
    },
    selectDate(e) {
      this.defaultDate = e;
      this.currentDate = formatDate(e, "yyyy-MM-dd"); //页面显示的日期
      this.dateVisible = false; // 关闭日期选择器
      this.mothPersonScheduling.forEach((item) => {
        if (item.date == getTimestamp(e) / 1000) {
          this.selectTimeParagraph = item.time;
        }
      });
    },

    getCurrentDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份从 0 开始计数，所以要加 1
      const day = date.getDate();
      return `${year}-${month}-${day}`;

      // 返回该日期的毫秒数
    },
    async getUserInfo(id) {
      let res = await queryOfflineConsultInfo({ id });
      if (res.code == 200) {
        this.info = res.data;
      }
    },
    convertSecondsToDate(seconds) {
      const milliseconds = seconds * 1000;
      const date = new Date(milliseconds);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    convertTimestampToYearMonth(timestamp) {
      const date = new Date(timestamp * 1000);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      return `${year}-${month}`;
    },

    //结束
    joinUrlImg,
    // 是否同意协议
    checkboxChange(e) {
      this.checkbox = e;
    },
    checkDet() {
      this.$router.push(`/consultantInfo?id=${this.info.id}`);
    },
    // 确认发起咨询
    async submit() {
      if (this.reservationMethod.id == 2) {
        let r = await queryUsernameGetInfo({
          username: this.user,
          password: this.password,
        });
        if (r.code == 200) {
          this.matchingInfo = r.data;
        } else {
          this.matchingInfo = {};
          return;
        }
      }
      let currentTime = Math.floor(new Date().getTime() / 1000);
      let params = {
        uid: this.INFO_USER.id, //预约用户id
        time_id: this.currentTimeParagraph.id, //预约时间段id
        type: this.reservationMethod.id, //预约方式
        question: this.questionDetail, //问题详情
        question_id: this.currentQuestionType.id, //问题类型id
        consult_id: this.$route.query.id, //咨询师id
        address: this.address,
        time: currentTime,
      };

      if (!this.currentDate) return this.$toast.fail("请选择预约日期！");
      if (!this.currentTimeParagraph)
        return this.$toast.fail("请选择预约时段！");
      if (!this.currentQuestionType.name)
        return this.$toast.fail("请选择问题类型！");
      if (!this.address) return this.$toast.fail("请输入地址！");
      if (!this.questionDetail) return this.$toast.fail("请描述问题！");
      if (!this.checkbox) return this.$toast.fail("请同意咨询服务协议");
      if (this.reservationMethod.id == 2) {
        if (!this.user) return this.$toast.fail("请输入预约账号！");
        if (!this.password) return this.$toast.fail("请输入账号密码！");
      }

      let dateString = `${this.currentDate} ${
        this.currentTimeParagraph.label.split("--")[0]
      }:00`;
      let date1 = Date.parse(dateString);
      if (isNaN(date1)) {
        return this.$toast.fail("日期解析失败，请检查选择的时间！");
      }
      if (date1 < new Date().getTime())
        return this.$toast.fail("不能预约已经过去的时间！");
      let res = await offlAppntSubmit(params);
      if (res.code == 200) {
        let data = {
          create_time: currentTime,
          expert_name: this.info.name,
          reservation_situation: this.reservationMethod.label,
          appointment_time: this.currentTimeParagraph.label,
          adress: this.address,
        };
        this.$router.push({
          path: "/subscribeSuccess",
          query: { obj: JSON.stringify(data) },
        });
      }
    },
    // 选择当前时段
    selectTimeParagraphOperate(item) {
      if (!item) return;
      this.currentTimeParagraph = item;

      this.timeVisible = false;
    },
    async getAddress() {
      const params = {
        key: "consult",
      };
      let res = await queryParSet(params);
      if (res.code == 200) {
        this.isAddress = res.data.is_address;
      }
    },
    // 显示哪个时间有排期
    formatter(day) {
      const month = day.date.getMonth() + 1;
      const date = day.date.getDate();

      if (
        new Date(this.year, month - 1, date + 1).getTime() <
        new Date().getTime()
      ) {
        day.type = "disabled";
      }
      this.canBeBooked.forEach((item) => {
        let m = item.date.split("-")[1];
        let d = item.date.split("-")[2];
        if (month == m && date == d) {
          day.topInfo = "有排期";
        }
      });
      return day;
    },

    // 选择预约方式
    async selectReservationMethod(e) {
      this.reservationMethod = e;
      this.visibleReservation = false;
    },
  },
};
</script>

<style lang="less" scoped>
@import "./css/index.less";
</style>
